<?php defined('SYSPATH') or die('No direct script access.');
/**
 * $Id: feed.php 50 2008-07-27 09:06:29Z geertdd $
 *
 * @package    PianissiBoard
 * @author     Geert De Deckere
 */
class Feed_Controller extends Controller {

	// Libraries
	public $cache;

	// Models
	public $topic;
	public $post;

	/**
	 * Feed constructor.
	 */
	public function __construct()
	{
		parent::__construct();

		// Send the right header
		header('Content-Type: text/xml; charset=utf-8');

		// Load libraries
		$this->cache = Cache::instance();

		// Load models
		$this->topic = new Topic_Model;
		$this->post = new Post_Model;
	}

	/**
	 * URL: /pianissiboard/feed
	 * Feed for the active topic list.
	 */
	public function index()
	{
		// No cached feed found
		if ( ! $feed = $this->cache->get('feed_index'))
		{
			// General feed info
			$info = array
			(
				'title'         => 'Active topics on PianissiBoard',
				'link'          => url::site('pianissiboard'),
				'pubDate'       => time(),
				'lastBuildDate' => time(),
			);

			// Feed items
			$items = array();

			foreach ($this->post->get(array('limit' => 5, 'order' => 'desc')) as $item)
			{
				$items[] = array
				(
					'pubDate'     => $item->date,
					'link'        => url::site('pianissiboard/topic/'.$item->topic_id.'/'.$item->topic_slug.'/post/'.$item->id),
					'title'       => html::specialchars($item->topic_title),
					'author'      => html::specialchars($item->author),
					'description' => html::specialchars($item->post),
				);
			}

			// Create the XML
			$feed = feed::create($info, $items);

			// Cache the feed
			$this->cache->set('feed_index', $feed, 'feed', 3600);
		}

		// Output the feed
		echo $feed;
	}

	/**
	 * URL: /pianissiboard/feed/topic/{id}
	 * Feed for one topic's posts.
	 */
	public function topic()
	{
		// Non-existing topic id
		if (($topic = $this->topic->get_by_id($this->uri->segment(4))) === FALSE)
			Event::run('system.404');

		// No cached feed found
		if ( ! $feed = $this->cache->get('feed_topic_'.$topic->id))
		{
			// General feed info
			$info = array
			(
				'title'         => html::specialchars($topic->title),
				'link'          => url::site('pianissiboard/topic/'.$topic->id.'/'.$topic->slug),
				'pubDate'       => time(),
				'lastBuildDate' => time(),
			);

			// Feed items
			$items = array();

			foreach ($this->post->get(array('topic_id' => $topic->id)) as $item)
			{
				$items[] = array
				(
					'pubDate'     => $item->date,
					'link'        => url::site('pianissiboard/topic/'.$topic->id.'/'.$topic->slug.'/post/'.$item->id),
					'title'       => html::specialchars('Reply from '.$item->author.' on “'.$topic->title.'”'),
					'author'      => html::specialchars($item->author),
					'description' => html::specialchars($item->post),
				);
			}

			// Create the XML
			$feed = feed::create($info, $items);

			// Cache the feed
			$this->cache->set('feed_topic_'.$topic->id, $feed, 'feed', 3600);
		}

		// Output the feed
		echo $feed;
	}

}